<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '入住' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
               label-width="80px">
        <el-form-item label="会员名称" prop="mebName">
          <el-input v-model="dataForm.mebName" placeholder="会员名称" @click.native="memberHandle()"/>
        </el-form-item>
        <el-form-item label="房型" prop="floorRoomName">
          <el-input v-model="dataForm.floorRoomName" placeholder="房型" @click.native="roomTypeHandle()"/>
        </el-form-item>
        <el-form-item label="时间段" prop="checkInPeriod">
          <el-date-picker
            v-model="dataForm.checkInPeriod"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="入住日期"
            end-placeholder="退房日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="this.isLoading">确定</el-button>
    </span>
      <room-type-visible v-if="roomTypeVisible" ref="roomType" @roomTypeCallback="roomTypeCallback"/>
      <member-visible v-if="memberVisible" ref="member" @memberCallback="memberCallback"/>
    </el-dialog>
  </div>
</template>

<script>
  import memberVisible from '@/components/member'
  import roomTypeVisible from '@/components/roomType'

  export default {
    data () {
      var validatePeriod = (rule, value, callback) => {
        if (this.dataForm.checkInPeriod[0] === this.dataForm.checkInPeriod[1]) {
          callback(new Error('日期不能相同'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        isLoading: false,
        roomTypeVisible: false,
        memberVisible: false,
        dataForm: {
          id: 0,
          memId: '',
          roomtypeId: '',
          checkinTime: '',
          superiorName: '',   // 上级名称
          mebName: '',        // 会员姓名
          floorRoomName: '',   // 楼号加房号
          checkInPeriod: [], // 入住时间段
          price: 0
        },
        dataRule: {
          mebName: [
            {required: true, message: '会员不能为空', trigger: 'change'}
          ],
          floorRoomName: [
            {required: true, message: '房型不能为空', trigger: 'change'}
          ],
          checkInPeriod: [
            {required: true, message: '时间段不能为空', trigger: 'blur'},
            { validator: validatePeriod, trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      roomTypeVisible,
      memberVisible
    },
    watch: {},
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.isLoading = false
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/tra/history/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.memId = data.history.memId
                this.dataForm.roomtypeId = data.history.roomtypeId
                this.dataForm.checkinTime = data.history.checkinTime
                this.dataForm.checkoutTime = data.history.checkoutTime
                this.dataForm.checkInPeriod.push(data.history.checkinTime)
                this.dataForm.checkInPeriod.push(data.history.checkoutTime)
                this.dataForm.mebName = data.history.mebName
                this.dataForm.superiorName = data.history.superiorName
                this.dataForm.floorRoomName = data.history.floorRoomName
              }
            })
          } else {
            this.checkInPeriodHandle()
          }
        })
      },
      // 二维码核验传值
      open (memberStr) {
        this.dataForm.id = 0
        this.visible = true
        this.isLoading = false
        let mebJSON = JSON.parse(memberStr)
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.dataForm.mebName = mebJSON.name
          this.dataForm.memId = mebJSON.id
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.isLoadingVisible()
            this.$http({
              url: this.$http.adornUrl(`/tra/history/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'mebId': this.dataForm.memId,
                'roomtypeId': this.dataForm.roomtypeId,
                'roomTypeIds': this.dataForm.roomtypeIds,
                'checkinTime': this.dataForm.checkInPeriod[0],
                'checkoutTime': this.dataForm.checkInPeriod[1],
                'price': this.dataForm.price,
                'isDel': 0
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '入住成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.isLoadingVisible()
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
                this.isLoadingVisible()
              }
            })
          }
        })
      },
      isLoadingVisible () {
        this.isLoading = !this.isLoading
      },
      memberHandle () {
        this.memberVisible = true
        this.$nextTick(() => {
          this.$refs.member.init()
        })
      },
      roomTypeHandle () {
        this.roomTypeVisible = true
        this.$nextTick(() => {
          this.$refs.roomType.init(this.dataForm.id)
        })
      },
      roomTypeCallback (rows) {
        this.dataForm.floorRoomName = ''
        this.dataForm.roomtypeIds = []
        this.dataForm.price = 0
        // 新增多条的操作
        for (let row of rows) {
          this.dataForm.floorRoomName += row.floor + '/' + row.name + '(' + row.def0 + ')' + ','
          if (row.def0 > 0) {
            for (let i = 0; i < row.def0; i++) {
              this.dataForm.roomtypeIds.push(row.id)
            }
          } else {
            // 单条的操作
            this.dataForm.roomtypeIds.push(row.id)
          }
          this.dataForm.price += row.price
        }
        // 修改的操作
        if (this.dataForm.roomtypeIds.length === 1) {
          this.dataForm.roomtypeId = this.dataForm.roomtypeIds[0]
        }
        this.dataForm.floorRoomName = this.dataForm.floorRoomName.substr(0, this.dataForm.floorRoomName.length - 1)
      },
      memberCallback (row) {
        this.dataForm.mebName = row.name
        this.dataForm.memId = row.id
        this.dataForm.superiorName = row.superiorName
      },
      checkInPeriodHandle () {
        let date = new Date()
        let startDate = date.toLocaleDateString().replace(new RegExp('/', 'g'), '-')
          .toString()
        let endDate = new Date(date.setDate(date.getDate() + 1)).toLocaleDateString()
          .replace(new RegExp('/', 'g'), '-').toString()
        this.dataForm.checkInPeriod.push(startDate)
        this.dataForm.checkInPeriod.push(endDate)
      },
      onClick () {
        if (this.dataForm.checkInPeriod[0] === this.dataForm.checkInPeriod[1]) {
          this.$message({
            message: '开始日期和结束日期不能一致',
            type: 'warning'
          })
        }
      }
    }
  }
</script>
